package com.bosssoft.trainee.gateway.util;

import cn.hutool.json.JSONUtil;
import com.bosssoft.trainee.mbg.result.CommonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Author: wuxin
 * @Project: rbac-SpringCloud
 * @Date: 2022/7/15
 * @Description:
 */
public class ResponseUtil {
    private ResponseUtil(){}
    @SneakyThrows
    public static Mono<Void> out(ServerHttpResponse response, CommonResult result) {
        ObjectMapper objectMapper=new ObjectMapper();
        byte[] bits = objectMapper.writeValueAsString(JSONUtil.parse(result)).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Cache-Control","no-cache");
        return response.writeWith(Mono.just(buffer));
    }
}
